package org.spring.node2.domain.order.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.spring.node2.domain.item.service.ItemService;
import org.spring.node2.domain.item.vo.ItemVO;
import org.spring.node2.domain.order.vo.OrderVO;
import org.spring.node2.domain.user.service.UserService;
import org.spring.node2.domain.user.vo.UserVO;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
@RequiredArgsConstructor
public class OrderService {

    private Map<Long, OrderVO> orderMap = new ConcurrentHashMap<>();

    private final ItemService itemService;
    private final UserService userService;

    //    @Transactional  // 使用事物注解保证 ACID
    public String create(Long userId, Long itemId) {
        ItemVO itemVO = itemService.queryItemById(itemId);
        UserVO userVO = userService.queryUserById(userId);

        // 下单逻辑...

        if (userVO.getMoney() < itemVO.getItemPrice()) {
            return userVO.getUsername() + "太穷了，买不起" + itemVO.getItemName();
        }

        // 创建订单，持久化到数据库中
        OrderVO orderVO = new OrderVO(userId, itemId);
        save(orderVO);
        userService.pay(userId, itemVO.getItemPrice());
        return userVO.getUsername() + "下单" + itemVO.getItemName();
    }

    private void save(OrderVO orderVO) {
        orderMap.put(orderVO.getOrderId(), orderVO);
    }
}
